package mil.af.amc.adpetracker.web.actions.User;

import mil.af.amc.adpetracker.web.actions.AbstractAction;
import mil.af.amc.adpetracker.model.User;
import mil.af.amc.adpetracker.service.UserService;
import mil.af.amc.adpetracker.service.ServiceException;
import org.apache.struts.action.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Please Fill in this Javadoc
 *
 * @author TSgt Jason Ferguson
 */

public class InprocessUserAction extends AbstractAction {

    private Log log = LogFactory.getLog(InprocessUserAction.class);

    private UserService userService;

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @Override
    public ActionForward execute(ActionMapping actionMapping, ActionForm actionForm, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {

        // we can reuse the user now, since the request is set up with mandatory values
        DynaActionForm form = (DynaActionForm) actionForm;
        User user = null;
        try {
            user = userService.inprocessUser(form.getMap());
        } catch (ServiceException e) {
            ActionMessage actionMessage = new ActionMessage(e.getKey());
            saveError(httpServletRequest, actionMessage);

            return actionMapping.getInputForward();
        }

        if (user == null) {

            log.debug("Unable to create user in inprocessUser method");
            ActionMessage actionMessage = new ActionMessage("error.inprocess.user");
            saveError(httpServletRequest, actionMessage);

            return actionMapping.getInputForward();
        }

        ActionMessage actionMessage = new ActionMessage("messages.user.success.inprocess", user.getDisplayName());
        saveError(httpServletRequest, actionMessage);

        return actionMapping.findForward("success");

    }
}
